package ccnu.agile.command.verlocitygeneric.impl;

import ccnu.agile.bean.exception.CAPDException;
import ccnu.agile.command.verlocitygeneric.IGenericCommand;
import ccnu.agile.config.velocity.VelocityConfig;
import ccnu.agile.constant.System;
import ccnu.agile.enums.PrivError;
import ccnu.agile.utils.LogUtils;
import ccnu.agile.utils.SpringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
 * @Description: 实体类文件生成命令实现类
 * @Author: JreamY
 * @Date: 2021/11/14
 **/
@Service(System.GenericCommandBean.ENTITY)
@ConditionalOnBean(VelocityConfig.class)
public class EntityGenericCommandImpl implements IGenericCommand {

    private volatile Template template;
    private volatile VelocityContext context;

    @Override
    public Template initTemplate() {

        if(template == null) {
            synchronized (this) {
                if(template == null) {
                    template = SpringUtils.getBean(System.VelocityBean.ENTITY_TEMPLATE, Template.class);
                }
            }
        }
        return template;
    }

    @Override
    public PrintWriter initWriter(String className) {
        PrintWriter writer;
        try {
            writer = new PrintWriter(
                    new File("src/main/java/ccnu/agile/bean/entities/" + className + "Entity.java")
            );
        } catch (FileNotFoundException e) {
            LogUtils.error("文件输出位置不存在：{}", e.toString());
            throw new CAPDException(PrivError.DIRECTORY_NOT_FOUND);
        }
        return writer;
    }

    @Override
    public VelocityContext initContext() {

        if(context == null) {
            synchronized (this) {
                if(context == null) {
                    context = SpringUtils.getBean(VelocityContext.class);
                }
            }
        }
        return context;
    }

    @Override
    public void afterReturn() {
        LogUtils.info(this, "Entity实体类文件生成成功");
    }
}
